<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" class="dataForm">
      <el-row>
        <el-col :span="24">
          <el-form-item :label="$t('SQL脚本')" prop="sql">
            <span slot="label">
              {{ $t('SQL脚本') }}
              <el-tooltip :content="$t('如果是主表id字段，别名必须是id')" placement="top">
                <i class="el-icon-question" />
              </el-tooltip>
            </span>
            <textarea ref="sqlcode" v-model="form.searchSql" class="codesql" style="height: 100px;width: 100%" />
          </el-form-item>
        </el-col>
      </el-row>
      <div class="area-header">
        <span class="area-header-title">{{ $t('字段列表') }}</span>
        <span style="float: right;font-size: 14px;">
          <template>
            <el-button type="primary" size="mini" @click="getColumnBySql">{{ $t('刷新') }}</el-button>
          </template>
        </span>
      </div>
      <el-table
        :data="form.fieldList"
        border
        class="nowrapTable formTable"
        max-height="230"
      >
        <el-table-column :label="$t('字段名称')" align="center">
          <template slot-scope="scope">
            {{ scope.row.name }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('字段别名')" align="center">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('字段别名') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'fieldList.' + scope.$index + '.remark'" :rules="fieldListRules.remark">
              <el-input v-model="scope.row.remark" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('字段类型')" align="center">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('字段类型') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'fieldList.' + scope.$index + '.type'" :rules="fieldListRules.type">
              <el-select v-model="scope.row.type" clearable :placeholder="$t('请选择')" style="width: 100%" @change="updateFormatValue(scope.row)">
                <el-option
                  v-for="field in filedTypeOptions"
                  :key="field.dictValue"
                  :label="$t(field.dictLabel)"
                  :value="field.dictValue"
                />
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('格式化')" align="center">
          <template slot-scope="scope">
            <el-form-item :prop="'fieldList.' + scope.$index + '.type'">
              <el-input v-if="scope.row.type === 'RQ' || scope.row.type === 'JE'" v-model="scope.row.format" />
              <el-select v-if="scope.row.type === 'ZD'" v-model="scope.row.format" value="" clearable filterable :placeholder="$t('请选择')" style="width: 100%">
                <el-option
                  v-for="dict in dictOptions"
                  :key="dict.dictType"
                  :label="$t(dict.dictName)"
                  :value="dict.dictType"
                >
                  <span style="float: left">{{ dict.dictName }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ dict.dictType }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('打开方式')" align="center">
          <template slot-scope="scope">
            <el-select v-model="scope.row.openType">
              <el-option v-for="dict in openType" :key="dict.dictValue" :value="dict.dictValue" :label="$t(dict.dictLabel)" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column :label="$t('打开页面')" align="center">
          <template slot-scope="scope">
            <el-input v-model="scope.row.link" />
          </template>
        </el-table-column>
        <el-table-column :label="$t('页面参数')" align="center">
          <template slot-scope="scope">
            <el-input v-model="scope.row.linkParams" />
          </template>
        </el-table-column>
        <el-table-column :label="$t('用户是否可见')" align="center" width="150">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.isShow"
              active-value="Y"
              inactive-value="N"
            />
          </template>
        </el-table-column>
        <el-table-column :label="$t('是否在列表展示')" align="center" width="150">
          <template slot-scope="scope">
            <el-switch
              v-if="scope.row.isShow === 'Y'"
              v-model="scope.row.isDisplayedInList"
              active-value="Y"
              inactive-value="N"
            />
          </template>
        </el-table-column>
        <el-table-column :label="$t('是否固定')" align="center" width="150">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.isFixed"
              active-value="Y"
              inactive-value="N"
            />
          </template>
        </el-table-column>
        <el-table-column :label="$t('排序')" align="center" width="100">
          <template slot-scope="scope">
            <el-input v-model="scope.row.sort" />
          </template>
        </el-table-column>
        <el-table-column :label="$t('默认宽度')" align="center" width="100">
          <template slot-scope="scope">
            <el-input v-model="scope.row.width" />
          </template>
        </el-table-column>
      </el-table>
    </el-form>
  </div>
</template>

<script>
  import 'codemirror/theme/ambiance.css'
  import 'codemirror/theme/idea.css'
  import 'codemirror/lib/codemirror.css'
  import 'codemirror/addon/hint/show-hint.css'
  import { getColumnBySql } from '@/api/system/search/searchSqlBase'
  import { mapState } from 'vuex'
  import { getOnlViewConfigByHeadId, saveOnlViewConfig } from '@/api/view/config/onlViewConfig'
  const CodeMirror = require('codemirror/lib/codemirror')
  require('codemirror/addon/edit/matchbrackets')
  require('codemirror/addon/selection/active-line')
  require('codemirror/mode/sql/sql')
  require('codemirror/addon/hint/show-hint')
  require('codemirror/addon/hint/sql-hint')
  export default {
    data() {
      return {
        form: {},
        filedTypeOptions: [],
        editor: null,
        fieldListRules: {
          remark: [{ required: true, message: this.$t('必填信息'),	trigger: 'change' }],
          type: [{ required: true, message: this.$t('必填信息'),	trigger: 'change' }]
        },
        openType: [
          {
            dictValue: 'notOpen',
            dictLabel: '不打开'
          },
          {
            dictValue: 'sheet',
            dictLabel: '新标签页打开'
          }
        ],
        loading: true
      }
    },
    computed: {
      ...mapState('dbAbout', ['head'])
    },
    created() {
      this.getDicts('search_field_type').then(response => {
        this.filedTypeOptions = response.data
      })
      if (this.head) {
        this.loading = true
        getOnlViewConfigByHeadId(this.head.id).then(res => {
          if (res.data) {
            this.form = res.data
            this.editor.setValue(this.form.searchSql)
          } else {
            this.reset()
          }
          this.loading = false
        })
      }
    },
    mounted() {
      const mime = 'text/x-mariadb'
      this.editor = CodeMirror.fromTextArea(this.$refs.sqlcode, {
        mode: mime,
        indentWithTabs: true,
        smartIndent: true,
        lineNumbers: true,
        matchBrackets: true,
        lineWrapping: true,
        autocorrect: true,
        spellcheck: true,
        extraKeys: { 'Ctrl': 'autocomplete' }, // 自定义快捷键
        hintOptions: { // 自定义提示选项
          // 当匹配只有一项的时候是否自动补全
          completeSingle: false
        }
      })
    },
    methods: {
      getColumnBySql: function() {
        this.form.searchSql = this.editor.getValue()
        if (this.form.searchSql === null || this.form.searchSql === '') {
          this.$message.error('sql脚本不能为空')
        } else {
          getColumnBySql(this.form).then(response => {
            // 保存之前配置的数据
            var fieldTempMap = {}
            for (var j = 0; j < this.form.fieldList.length; j++) {
              var filed = this.form.fieldList[j]
              fieldTempMap[filed.name] = filed
            }
            var fieldList = []
            for (var i = 0; i < response.data.length; i++) {
              var field = {}
              if (fieldTempMap[response.data[i]] !== null && fieldTempMap[response.data[i]] !== undefined) {
                field = fieldTempMap[response.data[i]]
                field.sort = (i + 1) * 10
              } else {
                field.name = response.data[i]
                field.remark = response.data[i]
                field.type = 'WB'
                field.isShow = 'Y'
                field.isDisplayedInList = 'Y'
                field.sort = (i + 1) * 10
                field.width = 200
                field['openType'] = 'notOpen'
              }
              fieldList.push(field)
            }
            fieldList.sort((field1, field2) => {
              return field1.sort - field2.sort
            })
            this.form.fieldList = fieldList
          })
        }
      },
      // 表单重置
      reset() {
        this.form = {
          searchSql: undefined,
          fieldList: [],
          createBy: undefined,
          createTime: undefined,
          updateBy: undefined,
          updateTime: undefined,
          delFlag: undefined
        }
        this.editor.setValue('')
        this.resetForm('form')
      },
      // 设置格式化字段默认值
      updateFormatValue: function(row) {
        if (row.type === 'JE') {
          row.format = '###,###.####'
        } else if (row.type === 'RQ') {
          row.format = 'yyyy-MM-dd'
        }
      },
      submitForm() {
        this.$refs.form.validate(valid => {
          if (valid) {
            this.loading = true
            this.form.tempId = this.head.id
            this.form.searchSql = this.editor.getValue()
            saveOnlViewConfig(this.form).then(() => {
              this.loading = false
            })
          }
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
/deep/.CodeMirror.cm-s-default.CodeMirror-wrap {
  height: 200px;
}
</style>
